package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.ArrowEntity;
import net.minecraft.entity.projectile.PersistentProjectileEntity;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.Vec3d;

public record MultiBowEnchantmentEffect(EnchantmentLevelBasedValue arrows) implements EnchantmentEntityEffect {
    public static final MapCodec<MultiBowEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("arrows").forGetter(MultiBowEnchantmentEffect::arrows)
            ).apply(instance, MultiBowEnchantmentEffect::new)
    );

    public static void initialize() {
        // MultiBow主要通过projectile_spawned事件触发
        // 这里保留为空，实际逻辑在apply方法中处理
    }

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        if (!(context.owner() instanceof PlayerEntity player)) {
            return;
        }

        // 当弓箭发射时触发多重射击
        // 计算额外箭矢数量（每级+1支箭）
        int extraArrows = level;

        // 发射额外的箭矢
        for (int i = 0; i < extraArrows; i++) {
            fireExtraArrow(world, player, i + 1, extraArrows);
        }

        // 播放额外的射击音效
        if (extraArrows > 0) {
            world.playSound(null, player.getX(), player.getY(), player.getZ(),
                    SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.PLAYERS,
                    0.3f, 0.4f / (world.getRandom().nextFloat() * 0.4f + 0.8f));
        }
    }

    /**
     * 发射额外的箭矢
     */
    private static void fireExtraArrow(ServerWorld world, PlayerEntity player, int arrowIndex, int totalExtraArrows) {
        // 创建箭矢
        ArrowEntity arrow = new ArrowEntity(net.minecraft.entity.EntityType.ARROW, world);
        arrow.setOwner(player);

        // 设置箭矢拾取规则
        arrow.pickupType = PersistentProjectileEntity.PickupPermission.CREATIVE_ONLY;

        // 计算散射角度
        float spreadAngle = calculateSpreadAngle(arrowIndex, totalExtraArrows);

        // 设置箭矢方向（添加散射）
        float yaw = player.getYaw() + spreadAngle;
        float pitch = player.getPitch();

        // 计算速度（使用标准弓箭速度）
        float velocity = 3.0f;
        arrow.setVelocity(player, pitch, yaw, 0.0f, velocity, 1.0f);

        // 设置暴击
        arrow.setCritical(true);

        // 生成箭矢
        world.spawnEntity(arrow);
    }

    /**
     * 计算散射角度
     */
    private static float calculateSpreadAngle(int arrowIndex, int totalArrows) {
        if (totalArrows <= 1) {
            return 0.0f;
        }

        // 总散射角度为30度
        float totalSpread = 30.0f;
        float angleStep = totalSpread / totalArrows;

        // 计算当前箭矢的角度偏移
        float baseOffset = -(totalSpread / 2.0f);
        return baseOffset + (arrowIndex * angleStep);
    }


    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 